package com.tarena.lbs.marketing.web.consumer;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.marketing.web.service.ActivityService;
import com.tarena.lbs.marketing.web.service.UserCouponsService;
import com.tarena.lbs.pojo.basic.event.LocationEvent;
import com.tarena.lbs.pojo.marketing.param.UserCouponsParam;
import com.tarena.lbs.pojo.marketing.po.ActivityPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class StoreLocationConsumer {
    @Autowired
    private UserCouponsService userCouponsService;
    @Autowired
    private ActivityService activityService;
    @StreamListener("marketing-stores-location-input")
    public void storeLocation(LocationEvent event){
        log.info("接收到用户定位消息：{}",event);
        //拿到定位店铺数据后的业务逻辑
        try{
            //1.拿到event中storeId
            Integer storeId = event.getStoreId();
            //2.读取当前店铺 绑定的所有活动 活动数组
            List<ActivityPO> activities=activityService.getActivitiesByStoreId(storeId);
            //3.查询到活动不为空的 循环这个活动 封装UserCoupnsParam复用领取方法
            if (CollectionUtils.isNotEmpty(activities)){
                for(ActivityPO activity:activities){
                    //每次循环组织一个UserCouponsParam
                    UserCouponsParam param=new UserCouponsParam();
                    param.setActivityId(activity.getId());
                    param.setUserId(event.getUserId());
                    param.setCouponId(activity.getRewardCouponId());
                    param.setShopId(storeId);//渠道 自动下发 2 优惠券券码
                    userCouponsService.getCoupon(param);
                }
            }
        }catch(BusinessException e){
            log.error("由于校验失败导致 自动营销下发优惠券失败",e);
        }catch (Exception e){
            log.error("由于系统其他原因导致下发优惠券失败",e);
        }
    }
}
